const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//为空判断函数
function isNull(arg1) {
    return !arg1 && arg1 !== 0 && typeof arg1 !== "boolean" ? true : false;
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

// 小程序专用 数据请求 wx.request
const httpRrquest = function (url, method, data) {
    var status = true;

    var promise = new Promise(function (resolve, reject) {
        wx.getNetworkType({
            success: function (res) {
                // 返回网络类型2g，3g，4g，wifi, none, unknown
                var networkType = res.networkType
                if (networkType == "none") {
                    wx.hideLoading();
                    //没有网络连接
                    wx.showModal({
                        title: '提示',
                        content: '网络连接失败,请检查您的网络设置',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                //返回res.confirm为true时，表示用户点击确定按钮
                                console.log('表示用户点击确定按钮')
                            }
                        }
                    })
                    status = false;
                } else if (networkType == "unknown") {
                    wx.hideLoading();
                    //未知的网络类型
                    wx.showModal({
                        title: '提示',
                        content: '未知的网络类型,请检查您的网络设置',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                //返回res.confirm为true时，表示用户点击确定按钮
                                console.log('表示用户点击确定按钮')
                            }
                        }
                    })
                    status = false;
                } else {
					wx.showNavigationBarLoading();
                    wx.showToast({
                        title: '加载中...',
                        icon: 'loading'
                    })
                    var token = wx.getStorageSync('token');
                    wx.request({
                        url: url,
                        data: data,
                        method: method,
                        header: reqHeader(),
                        //success: resolve,
                        success: function (response) {
                            setTimeout(function () {
                                wx.hideToast();
                            },500);
                            //判断数据是否请求成功
                            if (response.data.code == 1) {
                                resolve(response);
                            } else if (response.data.code == "1000" || response.data.code == "1001") {
                                //未登录或登录已失效
                                wx.redirectTo({
                                    url: '/pages/auth/auth'
                                })
                                return;
                                
                            } else if (response.data.code == "1002") {
                                //未登录或登录已失效
                                wx.showModal({
                                    title: '提示',
                                    content: '为确保能向您提供最准确的服务，请重新授权',
                                    showCancel: false,
                                    success: function (res) {
                                        if (res.confirm) {
                                            //跳转到认证页面
											
											var url = getCurPage();
											wx.redirectTo({
												url: '/pages/pauth/pauth?prev_url=' + url
											})
                                        } else {
                                            wx.switchTab({
                                                url: '/pages/index/index'
                                            })
                                        }
                                    }
                                })
                            } else { //其他错误提示
                                setTimeout(function () {
                                    //提示后台接口抛出的错误信息
                                    wx.showToast({
                                        title: response.data.msg,
                                        icon: 'none',
                                        duration: 2000
                                    })
                                }, 500);
                            }
                        },
                        fail: reject,
                        complete: function () {
                            wx.hideNavigationBarLoading();
                        }
                    })
                }
            }
        })
        return status
    });
    return promise;
};


// 小程序专用 数据请求 wx.uploadFile
const httpUpload = function (url, data) {
    var status = true;

    var promise = new Promise(function (resolve, reject) {
        wx.getNetworkType({
            success: function (res) {
                // 返回网络类型2g，3g，4g，wifi, none, unknown
                var networkType = res.networkType
                if (networkType == "none") {
                    wx.hideLoading();
                    //没有网络连接
                    wx.showModal({
                        title: '提示',
                        content: '网络连接失败,请检查您的网络设置',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                //返回res.confirm为true时，表示用户点击确定按钮
                                console.log('表示用户点击确定按钮')
                            }
                        }
                    })
                    status = false;
                } else if (networkType == "unknown") {
                    wx.hideLoading();
                    //未知的网络类型
                    wx.showModal({
                        title: '提示',
                        content: '未知的网络类型,请检查您的网络设置',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                //返回res.confirm为true时，表示用户点击确定按钮
                                console.log('表示用户点击确定按钮')
                            }
                        }
                    })
                    status = false;
                } else {
                    //选择图片
                    wx.chooseImage({
                        success: function (res) {
                            var tempFilePaths = res.tempFilePaths;
							wx.showNavigationBarLoading();
                            wx.showToast({
                                title: '上传中...',
                                icon: 'loading'
                            })
                            wx.uploadFile({
                                url: url,
                                filePath: tempFilePaths[0],
                                name: 'file',
                                header: reqHeader(),
                                formData: data,
                                //success: resolve,
                                success: function (response) {
                                    setTimeout(function () {
                                        wx.hideToast();
                                    }, 500);
                                    var response=JSON.parse(response.data);
                                    //console.log(response.code);
                                    //console.log(response.msg);
                                    //判断数据是否请求成功
                                    if (response.code == 1) {
                                        resolve(response);
                                    }else{
                                        setTimeout(function () {
                                            //提示后台接口抛出的错误信息
                                            wx.showToast({
                                                title: response.msg,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }, 500);
                                    }
                                },
                                fail: reject,
                                complete: function () {
                                    wx.hideNavigationBarLoading();
                                }
                            })
                        }
                    })
                }
            }
        })
        return status
    });
    return promise;
};

// header 头部
function reqHeader() {
    var header = {
        //'content-type': 'application/x-www-form-urlencoded'
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    }
    var token = wx.getStorageSync('token') || '';
    if (token) {
        header['token'] = token;
    }
    return header
}
//获取当前页面全路径
function getCurPage() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    var params = ''
    for (var i in options) {
        params += '-' + i + '|' + options[i]
    }
    if (params) {
        params = params.substring(1)
    }
    return [url, params]
}
module.exports = {
    formatTime: formatTime,
    isNull:isNull,
    httpRrquest: httpRrquest,
    httpUpload: httpUpload,
    getCurPage: getCurPage,
}